package com.ch.engine.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

/**
 * 初始化数据源
 *
 * @author zh
 * @date 2022/1/6 16:48
 */
@Configuration
@MapperScan({"com.ch.engine.**.mapper"})
@Slf4j
public class MybatisPlusConfigurer {

    /**
     * 配置分页拦截器
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return interceptor;
    }

    /**
     * 配置数据权限拦截器
     */
    @Bean
    public DataPermissionInterceptor dataPermissionInterceptor() {
        return new DataPermissionInterceptor();
    }

    /**
     * 配置文件yml中的默认数据源
     *
     * @return
     */
    @Bean(name = "defaultDataSource")
    public DataSource getDefaultDataSource(DefaultDatasourceProperties properties) {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(properties.getDriverClassName());
        dataSource.setJdbcUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setConnectionTestQuery("select 1");
        dataSource.setConnectionTimeout(3000);
        dataSource.setMaxLifetime(800_000);
        dataSource.setIdleTimeout(600_000);
        dataSource.setMaximumPoolSize(20);
        dataSource.setMinimumIdle(10);
        dataSource.setPoolName("vc-Hikari");
        dataSource.setPassword(properties.getPassword());
        return dataSource;
    }
}
